#!/usr/bin/env python3
"""
Simple AI Historical Simulation Platform Demo
A working demonstration of the core HDC functionality with historical figures.
"""

import sys
import os
import time
import numpy as np
from typing import Dict, Any, List

# Add current directory to Python path
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, current_dir)

# Import only the working HDC core
from src.hdc.core import HDCOperations


class SimpleHistoricalFigure:
    """Simple historical figure class for demonstration."""
    
    def __init__(self, name: str, traits: Dict[str, float], cultural_context: Dict[str, Any], knowledge_era: str):
        self.name = name
        self.traits = traits  # Big Five personality traits
        self.cultural_context = cultural_context
        self.knowledge_era = knowledge_era
        self.personality_vector = None
        
    def encode_personality(self, hdc: HDCOperations) -> np.ndarray:
        """Encode personality traits into HDC vector."""
        # Generate base trait vectors
        trait_vectors = []
        for trait, score in self.traits.items():
            # Create a unique vector for each trait
            trait_vector = hdc.generate_random_vector()
            weighted_vector = score * trait_vector
            trait_vectors.append(weighted_vector)
        
        # Bundle all traits into personality
        self.personality_vector = hdc.bundling(*trait_vectors)
        return self.personality_vector
    
    def get_response_context(self) -> str:
        """Get contextual information for response generation."""
        return f"""
You are {self.name} from the {self.knowledge_era} era.
Your personality traits:
- Openness: {self.traits.get('openness', 0.5):.2f}
- Conscientiousness: {self.traits.get('conscientiousness', 0.5):.2f}  
- Extraversion: {self.traits.get('extraversion', 0.5):.2f}
- Agreeableness: {self.traits.get('agreeableness', 0.5):.2f}
- Neuroticism: {self.traits.get('neuroticism', 0.5):.2f}

Cultural context: {self.cultural_context}
Respond authentically as this historical figure would, with knowledge limited to your time period.
        """


class SimpleAIHistoricalPlatform:
    """Simple AI Historical Simulation Platform."""
    
    def __init__(self):
        self.hdc = HDCOperations(dimension=10000)
        self.figures = {}
        self.session_data = {
            'interactions': 0,
            'start_time': time.time()
        }
        self._initialize_figures()
    
    def _initialize_figures(self):
        """Initialize pre-configured historical figures."""
        
        # Napoleon Bonaparte
        napoleon = SimpleHistoricalFigure(
            name="Napoleon Bonaparte",
            traits={
                'openness': 0.8,
                'conscientiousness': 0.9,
                'extraversion': 0.7, 
                'agreeableness': 0.3,
                'neuroticism': 0.4
            },
            cultural_context={
                'nationality': 'French',
                'social_class': 'Military/Political Elite',
                'values': 'Honor, Glory, Order, Merit'
            },
            knowledge_era="Early 19th Century (1769-1821)"
        )
        napoleon.encode_personality(self.hdc)
        self.figures['napoleon'] = napoleon
        
        # Albert Einstein  
        einstein = SimpleHistoricalFigure(
            name="Albert Einstein",
            traits={
                'openness': 0.95,
                'conscientiousness': 0.7,
                'extraversion': 0.4,
                'agreeableness': 0.6,
                'neuroticism': 0.3
            },
            cultural_context={
                'nationality': 'German-American',
                'profession': 'Theoretical Physicist',
                'values': 'Truth, Peace, Curiosity, Humanity'
            },
            knowledge_era="Early-Mid 20th Century (1879-1955)"
        )
        einstein.encode_personality(self.hdc)
        self.figures['einstein'] = einstein
        
        # William Shakespeare
        shakespeare = SimpleHistoricalFigure(
            name="William Shakespeare", 
            traits={
                'openness': 0.9,
                'conscientiousness': 0.8,
                'extraversion': 0.6,
                'agreeableness': 0.7,
                'neuroticism': 0.4
            },
            cultural_context={
                'nationality': 'English',
                'profession': 'Playwright and Poet',
                'values': 'Art, Beauty, Human Nature, Drama'
            },
            knowledge_era="Late 16th - Early 17th Century (1564-1616)"
        )
        shakespeare.encode_personality(self.hdc)
        self.figures['shakespeare'] = shakespeare
    
    def list_figures(self):
        """List available historical figures."""
        print("\n🎭 Available Historical Figures:")
        print("=" * 50)
        
        for key, figure in self.figures.items():
            print(f"\n👤 {figure.name}")
            print(f"   Era: {figure.knowledge_era}")
            print(f"   Command: {key}")
            
            # Show personality summary
            traits_summary = []
            for trait, score in figure.traits.items():
                if score > 0.7:
                    traits_summary.append(f"High {trait.title()}")
                elif score < 0.4:
                    traits_summary.append(f"Low {trait.title()}")
            
            if traits_summary:
                print(f"   Traits: {', '.join(traits_summary)}")
    
    def get_figure(self, figure_name: str) -> SimpleHistoricalFigure:
        """Get a historical figure by name/key."""
        return self.figures.get(figure_name.lower())
    
    def simulate_conversation(self, figure_name: str, user_message: str) -> Dict[str, Any]:
        """Simulate a conversation with a historical figure."""
        figure = self.get_figure(figure_name)
        if not figure:
            return {
                'error': f"Figure '{figure_name}' not found. Available: {list(self.figures.keys())}"
            }
        
        # Record interaction
        self.session_data['interactions'] += 1
        
        # Generate personality-influenced response (simplified)
        response_context = figure.get_response_context()
        
        # For demo, create context-appropriate responses
        responses = self._generate_demo_response(figure, user_message)
        
        return {
            'figure': figure.name,
            'era': figure.knowledge_era,
            'user_message': user_message,
            'response': responses,
            'personality_similarity': self._calculate_personality_metrics(figure),
            'interaction_number': self.session_data['interactions']
        }
    
    def _generate_demo_response(self, figure: SimpleHistoricalFigure, message: str) -> str:
        """Generate demo responses based on figure personality."""
        
        if figure.name == "Napoleon Bonaparte":
            if any(word in message.lower() for word in ['leadership', 'lead', 'command']):
                return "Leadership is the art of getting someone else to do something you want done because he wants to do it. A leader is a dealer in hope. I have learned that in war, the moral is to the physical as three is to one."
            elif any(word in message.lower() for word in ['strategy', 'war', 'battle']):
                return "I make my plans from the reports of my scouts. Strategy is the art of making use of time and space. I am less concerned with the former than the latter. Space we can recover, lost time never."
            elif any(word in message.lower() for word in ['power', 'empire']):
                return "Power is my mistress. I have worked too hard at her conquest to allow anyone to take her away from me. Glory is fleeting, but obscurity is forever."
            else:
                return "Mon ami, remember that an army marches on its stomach, but a mind advances on ideas. What specific aspect of leadership or strategy interests you?"
        
        elif figure.name == "Albert Einstein":
            if any(word in message.lower() for word in ['science', 'physics', 'relativity']):
                return "The important thing is not to stop questioning. Science is a wonderful thing if one does not have to earn one's living at it. The most beautiful thing we can experience is the mysterious."
            elif any(word in message.lower() for word in ['imagination', 'creativity']):
                return "Imagination is more important than knowledge. Knowledge is limited, whereas imagination extends throughout the world, stimulating progress and evolution."
            elif any(word in message.lower() for word in ['peace', 'war', 'humanity']):
                return "Peace cannot be kept by force; it can only be achieved by understanding. A human being is part of the whole called by us universe."
            else:
                return "Curious minds seek understanding. What puzzles you about the nature of our universe, or perhaps about the relationship between science and humanity?"
        
        elif figure.name == "William Shakespeare":
            if any(word in message.lower() for word in ['love', 'romance']):
                return "But love is blind, and lovers cannot see the pretty follies that themselves commit. The course of true love never did run smooth, yet it remains the greatest of human experiences."
            elif any(word in message.lower() for word in ['writing', 'poetry', 'art']):
                return "All the world's a stage, and all the men and women merely players. In poetry and plays, we capture the essence of the human condition, with all its follies and grandeur."
            elif any(word in message.lower() for word in ['life', 'human', 'nature']):
                return "To be, or not to be, that is the question. Life is but a walking shadow, a poor player that struts and frets his hour upon the stage. Yet in that brief time, what stories we might tell!"
            else:
                return "Good morrow! What themes of human nature or artistic expression would thou explore with this humble playwright?"
        
        return f"{figure.name} reflects thoughtfully on your question: '{message}' - and invites you to explore deeper aspects of {figure.knowledge_era} wisdom."
    
    def _calculate_personality_metrics(self, figure: SimpleHistoricalFigure) -> Dict[str, float]:
        """Calculate personality similarity metrics."""
        if figure.personality_vector is None:
            return {'error': 'Personality not encoded'}
        
        # Compare with other figures for context
        similarities = {}
        for other_name, other_figure in self.figures.items():
            if other_figure != figure and other_figure.personality_vector is not None:
                similarity = self.hdc.cosine_similarity(
                    figure.personality_vector, 
                    other_figure.personality_vector
                )
                similarities[other_name] = similarity
        
        return {
            'personality_strength': float(np.linalg.norm(figure.personality_vector)),
            'cross_figure_similarities': similarities
        }
    
    def get_platform_status(self) -> Dict[str, Any]:
        """Get platform status and metrics."""
        return {
            'platform': 'AI Historical Simulation Platform',
            'version': '1.0.0',
            'uptime_seconds': time.time() - self.session_data['start_time'],
            'total_interactions': self.session_data['interactions'],
            'available_figures': len(self.figures),
            'hdc_dimension': self.hdc.dimension,
            'status': 'Operational'
        }


def interactive_chat_mode():
    """Interactive chat mode with historical figures."""
    print("\n🎭 AI Historical Simulation Platform - Interactive Chat")
    print("=" * 60)
    print("Chat with historical figures! Type 'help' for commands.")
    
    platform = SimpleAIHistoricalPlatform()
    current_figure = None
    
    # Show available figures
    platform.list_figures()
    
    print(f"\n💬 Chat Commands:")
    print(f"  'select <figure>' - Choose a historical figure")
    print(f"  'figures' - List available figures") 
    print(f"  'status' - Show platform status")
    print(f"  'help' - Show this help")
    print(f"  'quit' or 'exit' - Exit the chat")
    
    while True:
        if current_figure:
            prompt = f"\n[{current_figure}] You: "
        else:
            prompt = f"\n[Select a figure] You: "
        
        try:
            user_input = input(prompt).strip()
        except KeyboardInterrupt:
            print(f"\n👋 Goodbye!")
            break
        
        if not user_input:
            continue
            
        # Handle commands
        if user_input.lower() in ['quit', 'exit', 'bye']:
            print(f"\n👋 Farewell! May the wisdom of history guide you!")
            break
            
        elif user_input.lower() == 'help':
            print(f"\n💡 Available Commands:")
            print(f"  'select napoleon' - Chat with Napoleon Bonaparte")
            print(f"  'select einstein' - Chat with Albert Einstein")
            print(f"  'select shakespeare' - Chat with William Shakespeare")
            print(f"  'figures' - List all available figures")
            print(f"  'status' - Show platform status")
            continue
            
        elif user_input.lower() == 'figures':
            platform.list_figures()
            continue
            
        elif user_input.lower() == 'status':
            status = platform.get_platform_status()
            print(f"\n📊 Platform Status:")
            for key, value in status.items():
                print(f"  {key}: {value}")
            continue
            
        elif user_input.lower().startswith('select '):
            figure_name = user_input[7:].strip()
            if platform.get_figure(figure_name):
                current_figure = figure_name
                print(f"\n✅ Now chatting with {platform.get_figure(figure_name).name}")
                print(f"Era: {platform.get_figure(figure_name).knowledge_era}")
                print(f"Ask them anything about their time, ideas, or experiences!")
            else:
                print(f"❌ Figure '{figure_name}' not found.")
                platform.list_figures()
            continue
        
        # Chat with current figure
        if current_figure:
            response_data = platform.simulate_conversation(current_figure, user_input)
            
            if 'error' in response_data:
                print(f"❌ {response_data['error']}")
                current_figure = None
                continue
            
            print(f"\n{response_data['figure']}: {response_data['response']}")
            
            # Show metrics occasionally
            if response_data['interaction_number'] % 3 == 0:
                metrics = response_data['personality_similarity']
                if 'cross_figure_similarities' in metrics:
                    print(f"\n📊 Personality Analysis:")
                    for other, similarity in metrics['cross_figure_similarities'].items():
                        print(f"  Similarity to {other}: {similarity:.3f}")
        else:
            print(f"❌ Please select a historical figure first using 'select <name>'")


def demo_mode():
    """Run demonstration scenarios."""
    print("\n🎬 AI Historical Simulation Platform - Demo Mode")
    print("=" * 55)
    
    platform = SimpleAIHistoricalPlatform()
    
    scenarios = [
        ("Napoleon", "What makes a great leader?"),
        ("Einstein", "How do you approach complex problems?"),
        ("Shakespeare", "What inspires great art?"),
        ("Napoleon", "How do you handle failure?"),
        ("Einstein", "What role does imagination play in science?"),
    ]
    
    print("🎭 Running demonstration conversations...\n")
    
    for i, (figure_key, question) in enumerate(scenarios, 1):
        print(f"📝 Scenario {i}: {question}")
        print(f"👤 Figure: {platform.get_figure(figure_key).name}")
        print("-" * 40)
        
        response_data = platform.simulate_conversation(figure_key, question)
        print(f"💭 Response: {response_data['response']}\n")
        
        time.sleep(1)  # Brief pause for readability
    
    # Show final platform status
    status = platform.get_platform_status()
    print("📊 Demo Completed - Platform Status:")
    for key, value in status.items():
        print(f"  {key}: {value}")


def main():
    """Main application entry point."""
    print("""
╔══════════════════════════════════════════════════════════════╗
║                                                              ║
║  🎭 AI Historical Simulation Platform                        ║
║                                                              ║
║  让有趣的灵魂跨越时空在当下聚首                                ║
║  Let fascinating souls gather across time in the present    ║
║                                                              ║
╚══════════════════════════════════════════════════════════════╝
""")
    
    if len(sys.argv) > 1:
        command = sys.argv[1].lower()
        
        if command == 'chat':
            interactive_chat_mode()
        elif command == 'demo':
            demo_mode()
        elif command == 'figures':
            platform = SimpleAIHistoricalPlatform()
            platform.list_figures()
        elif command == 'status':
            platform = SimpleAIHistoricalPlatform()
            status = platform.get_platform_status()
            print("\n📊 Platform Status:")
            for key, value in status.items():
                print(f"  {key}: {value}")
        else:
            print(f"❌ Unknown command: {command}")
            print("Available commands: chat, demo, figures, status")
    else:
        # Interactive mode selection
        print("\n🚀 Choose an option:")
        print("1. 💬 Interactive Chat - Talk with historical figures")
        print("2. 🎬 Demo Mode - Watch pre-configured conversations")
        print("3. 📋 List Figures - See available historical figures")
        print("4. 📊 Platform Status - View system information")
        print("5. ❌ Exit")
        
        try:
            choice = input("\nEnter your choice (1-5): ").strip()
            
            if choice == '1':
                interactive_chat_mode()
            elif choice == '2':
                demo_mode()
            elif choice == '3':
                platform = SimpleAIHistoricalPlatform()
                platform.list_figures()
            elif choice == '4':
                platform = SimpleAIHistoricalPlatform()
                status = platform.get_platform_status()
                print("\n📊 Platform Status:")
                for key, value in status.items():
                    print(f"  {key}: {value}")
            elif choice == '5':
                print("👋 Goodbye!")
            else:
                print("❌ Invalid choice. Please select 1-5.")
                
        except KeyboardInterrupt:
            print("\n👋 Goodbye!")


if __name__ == "__main__":
    main()